#include "UdpServer.hpp"
#include"Log.hpp"

void Usage(string proc)
{
    cout<<"Usage : "<<proc<<"prot[1024+]"<<endl;
}

string Handler(const string &str)
{
    string res = "Server get a message: ";
    res +=str;
    cout<<res<<endl;
    return res;
}

bool SafeCheck(const string &cmd)
{
    vector<string> key_word={
        "rm","mv","cp","kill","sudo","unlink","uninstall","apt"
    };
    for(auto word:key_word)
    {
        auto pos = cmd.find(word);
        if(pos != string::npos)
            return false;
    }
    return true;
}

string ExcuteCommand(const string &cmd)
{
    if(!SafeCheck(cmd)) return "bad man";

    FILE *fp = popen(cmd.c_str(), "r");
    if(fp == nullptr)
    {
        perror("popen");
        return "error";
    }
    string result;
    char buffer[4096];
    while(true)
    {
        char *res = fgets(buffer, sizeof(buffer), fp);
        if(res == nullptr) break;
        result += buffer;
    }
    pclose(fp);
    return result;
}

int main(int argc, char *argv[])
{
    if(argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    uint16_t port = stoi(argv[1]);

    unique_ptr<UdpServer> svr(new UdpServer(port));

    svr->Init();

    svr->Run(Handler);
    return  0;
}